Swift / C – Lock macOS programmatically

PrivateFrameworks are always a joy.

Today, for a personal project I discovered how to use private Login.framework to lock programmatically via code (Swift or C) the screen of my mac book.

The method is called “SACLockScreenImmediate“.

You can find a more detailed list of Private Headers on this fork: https://github.com/elpsk/macOS_headers/tree/master/macOS/PrivateFrameworks

Swift code:

import Foundation

func lock() {
let libHandle = dlopen("/System/Library/PrivateFrameworks/login.framework/Versions/Current/login", RTLD_LAZY)
let sym = dlsym(libHandle, "SACLockScreenImmediate")
typealias myFunction = @convention(c) () -> Void

let SACLockScreenImmediate = unsafeBitCast(sym, to: myFunction.self)
SACLockScreenImmediate()
}

lock()

Or if you prefer, this is the C version:

C code:

extern int SACLockScreenImmediate ( void );

int main ( ) {
return SACLockScreenImmediate();
}

Remember to compile using the clang command, like this:

$ clang -F /System/Library/PrivateFrameworks -framework login -o lockscreen lockscreen.c

Enjoy temporized lock screens!